package com.shlh.saas.controller;

import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.EmailSendRecord;
import com.shlh.saas.entity.User;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.entity.UserEmail;
import com.shlh.saas.model.dto.EmailVerificationDTO;
import com.shlh.saas.model.dto.CustomEmailSendDTO;
import com.shlh.saas.service.EmailService;
import com.shlh.saas.service.EmailVerificationService;
import com.shlh.saas.service.UserBalanceService;
import com.shlh.saas.service.UserService;
import com.shlh.saas.service.CustomEmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 邮件控制器
 */
@RestController
@RequestMapping("/email")
public class EmailController {

    private static final Logger log = LoggerFactory.getLogger(EmailController.class);

    @Autowired
    private EmailService emailService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserBalanceService userBalanceService;

    @Autowired
    private EmailVerificationService emailVerificationService;

    @Autowired
    private CustomEmailService customEmailService;

    @Value("${file.upload.attachments-path}")
    private String attachmentsPath;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 发送邮件 - 处理multipart/form-data格式（用于含附件的请求）
     */
//    @PostMapping("/send")
//    public Result<Boolean> sendEmail(
//            @RequestParam("recipients") String recipientsParam,
//            @RequestParam("subject") String subjectParam,
//            @RequestParam("content") String contentParam,
//            @RequestParam(value = "attachments", required = false) List<MultipartFile> attachments) {
//        try {
//            // 从ThreadLocal获取用户ID
//            Long userId = UserContext.getUserId();
//            if (userId == null) {
//                log.error("获取用户ID失败，用户未登录或登录已过期");
//                return Result.error("未登录或登录已过期");
//            }
//
//            // 获取用户信息
//            User user = userService.getUserById(userId);
//            if (user == null) {
//                log.error("用户ID({})不存在", userId);
//                return Result.error("用户不存在");
//            }
//
//            String phone = user.getPhone();
//
//            // 检查用户邮件余额
//            UserBalance userBalance = userBalanceService.getUserBalance(phone);
//            if (userBalance == null || userBalance.getEmailSendRemaining() <= 0) {
//                return Result.error("邮件余额不足，请购买邮件套餐");
//            }
//
//            // 验证必要参数
//            if (recipientsParam == null || subjectParam == null || contentParam == null) {
//                log.error("邮件参数不完整: recipients={}, subject={}, content存在={}",
//                        recipientsParam, subjectParam, (contentParam != null));
//                return Result.error("邮件参数不完整");
//            }
//
//            // 判断是否有附件并发送邮件
//            boolean success;
//            if (attachments != null && !attachments.isEmpty()) {
//                success = emailService.sendAttachmentEmail(recipientsParam, subjectParam, contentParam, attachments, userId, phone);
//            } else {
//                success = emailService.sendHtmlEmail(recipientsParam, subjectParam, contentParam, userId, phone);
//            }
//
//            if (success) {
//                return Result.success(true, "邮件发送成功");
//            } else {
//                return Result.error("邮件发送失败，请稍后重试");
//            }
//        } catch (Exception e) {
//            log.error("发送邮件时发生异常: {}", e.getMessage(), e);
//            return Result.error("邮件发送失败，请稍后重试");
//        }
//    }

    /**
     * 发送邮件 - 处理application/json格式（用于纯文本邮件）
     */
//    @PostMapping("/send-json")
//    public Result<Boolean> sendEmailJson(@RequestBody Map<String, Object> jsonData) {
//        try {
//            // 从ThreadLocal获取用户ID
//            Long userId = UserContext.getUserId();
//            if (userId == null) {
//                log.error("获取用户ID失败，用户未登录或登录已过期");
//                return Result.error("未登录或登录已过期");
//            }
//
//            // 获取用户信息
//            User user = userService.getUserById(userId);
//            if (user == null) {
//                log.error("用户ID({})不存在", userId);
//                return Result.error("用户不存在");
//            }
//
//            String phone = user.getPhone();
//
//            // 检查用户邮件余额
//            UserBalance userBalance = userBalanceService.getUserBalance(phone);
//            if (userBalance == null || userBalance.getEmailSendRemaining() <= 0) {
//                return Result.error("邮件余额不足，请购买邮件套餐");
//            }
//
//            // 处理JSON格式的请求
//            String recipients = (String) jsonData.get("recipient");
//            String subject = (String) jsonData.get("subject");
//            String content = (String) jsonData.get("content");
//            log.info("接收到JSON格式的邮件发送请求");
//
//            // 验证必要参数
//            if (recipients == null || subject == null || content == null) {
//                log.error("邮件参数不完整: recipients={}, subject={}, content存在={}",
//                        recipients, subject, (content != null));
//                return Result.error("邮件参数不完整");
//            }
//
//            // 发送纯文本邮件
//            boolean success = emailService.sendHtmlEmail(recipients, subject, content, userId, phone);
//
//            if (success) {
//                return Result.success(true, "邮件发送成功");
//            } else {
//                return Result.error("邮件发送失败，请稍后重试");
//            }
//        } catch (Exception e) {
//            log.error("发送邮件时发生异常: {}", e.getMessage(), e);
//            return Result.error("邮件发送失败，请稍后重试");
//        }
//    }

    /**
     * 定时发送邮件 - 处理multipart/form-data格式（用于含附件的请求）
     */
//    @PostMapping("/schedule-send")
//    public Result<Boolean> scheduleSendEmail(
//            @RequestParam("recipients") String recipientsParam,
//            @RequestParam("subject") String subjectParam,
//            @RequestParam("content") String contentParam,
//            @RequestParam("scheduledDate") String scheduledDateParam,
//            @RequestParam(value = "timezone", defaultValue = "UTC+8") String timezoneParam,
//            @RequestParam(value = "attachments", required = false) List<MultipartFile> attachments) {
//        try {
//            // 从ThreadLocal获取用户ID
//            Long userId = UserContext.getUserId();
//            if (userId == null) {
//                log.error("获取用户ID失败，用户未登录或登录已过期");
//                return Result.error("未登录或登录已过期");
//            }
//
//            // 获取用户信息
//            User user = userService.getUserById(userId);
//            if (user == null) {
//                log.error("用户ID({})不存在", userId);
//                return Result.error("用户不存在");
//            }
//
//            String phone = user.getPhone();
//
//            // 检查用户邮件余额
//            UserBalance userBalance = userBalanceService.getUserBalance(phone);
//            if (userBalance == null || userBalance.getEmailSendRemaining() <= 0) {
//                return Result.error("邮件余额不足，请购买邮件套餐");
//            }
//
//            // 验证必要参数
//            if (recipientsParam == null || subjectParam == null || contentParam == null || scheduledDateParam == null) {
//                log.error("邮件参数不完整: recipients={}, subject={}, content存在={}, scheduledDate={}",
//                        recipientsParam, subjectParam, (contentParam != null), scheduledDateParam);
//                return Result.error("邮件参数不完整");
//            }
//
//            // 解析定时发送时间
//            LocalDateTime scheduledDateTime = parseScheduledDate(scheduledDateParam, timezoneParam);
//
//            // 保存定时发送任务
//            boolean success;
//            if (attachments != null && !attachments.isEmpty()) {
//                success = emailService.scheduleAttachmentEmail(recipientsParam, subjectParam, contentParam, attachments, scheduledDateTime, userId, phone);
//            } else {
//                success = emailService.scheduleHtmlEmail(recipientsParam, subjectParam, contentParam, scheduledDateTime, userId, phone);
//            }
//
//            if (success) {
//                return Result.success(true, "邮件已安排定时发送");
//            } else {
//                return Result.error("安排定时发送失败，请稍后重试");
//            }
//        } catch (Exception e) {
//            log.error("安排定时发送邮件时发生异常: {}", e.getMessage(), e);
//            return Result.error("安排定时发送失败，请稍后重试");
//        }
//    }
//
//    /**
//     * 定时发送邮件 - 处理application/json格式（用于纯文本邮件）
//     */
//    @PostMapping("/schedule-send-json")
//    public Result<Boolean> scheduleSendEmailJson(@RequestBody Map<String, Object> jsonData) {
//        try {
//            // 从ThreadLocal获取用户ID
//            Long userId = UserContext.getUserId();
//            if (userId == null) {
//                log.error("获取用户ID失败，用户未登录或登录已过期");
//                return Result.error("未登录或登录已过期");
//            }
//
//            // 获取用户信息
//            User user = userService.getUserById(userId);
//            if (user == null) {
//                log.error("用户ID({})不存在", userId);
//                return Result.error("用户不存在");
//            }
//
//            String phone = user.getPhone();
//
//            // 检查用户邮件余额
//            UserBalance userBalance = userBalanceService.getUserBalance(phone);
//            if (userBalance == null || userBalance.getEmailSendRemaining() <= 0) {
//                return Result.error("邮件余额不足，请购买邮件套餐");
//            }
//
//            // 处理JSON格式的请求
//            String recipients = (String) jsonData.get("recipient");
//            String subject = (String) jsonData.get("subject");
//            String content = (String) jsonData.get("content");
//            String scheduledDateStr = (String) jsonData.get("scheduledDate");
//            String timezone = (String) jsonData.get("timezone");
//            if (timezone == null) timezone = "UTC+8";
//
//            log.info("接收到JSON格式的定时邮件发送请求");
//
//            // 验证必要参数
//            if (recipients == null || subject == null || content == null || scheduledDateStr == null) {
//                log.error("邮件参数不完整: recipients={}, subject={}, content存在={}, scheduledDate={}",
//                        recipients, subject, (content != null), scheduledDateStr);
//                return Result.error("邮件参数不完整");
//            }
//
//            // 解析定时发送时间
//            LocalDateTime scheduledDateTime = parseScheduledDate(scheduledDateStr, timezone);
//
//            // 安排定时发送
//            boolean success = emailService.scheduleHtmlEmail(recipients, subject, content, scheduledDateTime, userId, phone);
//
//            if (success) {
//                return Result.success(true, "邮件已安排定时发送");
//            } else {
//                return Result.error("安排定时发送失败，请稍后重试");
//            }
//        } catch (Exception e) {
//            log.error("安排定时发送邮件时发生异常: {}", e.getMessage(), e);
//            return Result.error("安排定时发送失败，请稍后重试");
//        }
//    }

    /**
     * 获取邮件发送记录
     */
    @GetMapping("/send-records")
    public Result<Map<String, Object>> getEmailSendRecords(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                log.error("获取用户ID失败，用户未登录或登录已过期");
                return Result.error("未登录或登录已过期");
            }

            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                log.error("用户ID({})不存在", userId);
                return Result.error("用户不存在");
            }

            String phone = user.getPhone();

            // 获取邮件发送记录
            Map<String, Object> records = emailService.getEmailSendRecords(userId, phone, page, size);

            return Result.success(records);
        } catch (Exception e) {
            log.error("获取邮件发送记录时发生异常: {}", e.getMessage(), e);
            return Result.error("获取邮件发送记录失败，请稍后重试");
        }
    }

    /**
     * 删除邮件发送记录
     */
    @DeleteMapping("/send-records/{id}")
    public Result<Boolean> deleteEmailRecord(@PathVariable("id") Long id) {
        try {
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                log.error("获取用户ID失败，用户未登录或登录已过期");
                return Result.error("未登录或登录已过期");
            }

            // 删除邮件记录
            boolean success = emailService.deleteEmailRecord(id, userId);

            if (success) {
                return Result.success(true, "删除成功");
            } else {
                return Result.error("删除失败，记录不存在或已被删除");
            }
        } catch (Exception e) {
            log.error("删除邮件发送记录时发生异常: {}", e.getMessage(), e);
            return Result.error("删除邮件发送记录失败，请稍后重试");
        }
    }

    /**
     * 获取用户邮件配额
     */
    @GetMapping("/quota")
    public Result<Map<String, Object>> getEmailQuota() {
        try {
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                log.error("获取用户ID失败，用户未登录或登录已过期");
                return Result.error("未登录或登录已过期");
            }

            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                log.error("用户ID({})不存在", userId);
                return Result.error("用户不存在");
            }

            String phone = user.getPhone();

            // 获取用户余额信息
            UserBalance userBalance = userBalanceService.getUserBalance(phone);

            Map<String, Object> result = new HashMap<>();
            if (userBalance != null) {
                result.put("emailSendRemaining", userBalance.getEmailSendRemaining());
                result.put("emailPackageLevel", userBalance.getEmailPackageLevel());
                result.put("emailPackageExpireTime", userBalance.getEmailPackageExpireTime());
            } else {
                result.put("emailSendRemaining", 0);
                result.put("emailPackageLevel", 0);
                result.put("emailPackageExpireTime", null);
            }

            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户邮件配额时发生异常: {}", e.getMessage(), e);
            return Result.error("获取用户邮件配额失败，请稍后重试");
        }
    }

    /**
     * 解析定时发送时间
     *
     * @param dateStr  日期字符串
     * @param timezone 时区
     * @return LocalDateTime
     */
    private LocalDateTime parseScheduledDate(String dateStr, String timezone) {
        try {
            // 将ISO格式日期字符串解析为LocalDateTime
            LocalDateTime dateTime = LocalDateTime.parse(dateStr);

            // 处理时区
            if (timezone != null && !timezone.equals("auto")) {
                // 提取时区偏移量
                int offset = 0;
                if (timezone.startsWith("UTC+")) {
                    offset = Integer.parseInt(timezone.substring(4));
                } else if (timezone.startsWith("UTC-")) {
                    offset = -Integer.parseInt(timezone.substring(4));
                }

                // 应用时区偏移
                ZoneId zoneId = ZoneId.of("UTC" + (offset >= 0 ? "+" : "") + offset);
                dateTime = dateTime.atZone(zoneId).withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
            }

            return dateTime;
        } catch (Exception e) {
            log.error("解析定时发送时间失败: {}", e.getMessage(), e);
            // 解析失败时返回一个默认时间（当前时间后10分钟）
            return LocalDateTime.now().plusMinutes(10);
        }
    }

    /**
     * 获取所有邮件发送记录（不分页，用于统计和图表）
     */
    @GetMapping("/all-send-records")
    public Result<List<EmailSendRecord>> getAllEmailSendRecords() {
        try {
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                log.error("获取用户ID失败，用户未登录或登录已过期");
                return Result.error("未登录或登录已过期");
            }

            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                log.error("用户ID({})不存在", userId);
                return Result.error("用户不存在");
            }

            String phone = user.getPhone();

            // 获取所有邮件记录（不分页）
            List<EmailSendRecord> records = emailService.getAllEmailSendRecords(userId, phone);

            return Result.success(records);
        } catch (Exception e) {
            log.error("获取所有邮件发送记录时发生异常: {}", e.getMessage(), e);
            return Result.error("获取邮件发送记录失败，请稍后重试");
        }
    }

    /**
     * 验证邮箱及授权码是否有效
     */
    @PostMapping("/verify-credentials")
    public Result<Boolean> verifyEmailCredentials(@RequestBody EmailVerificationDTO emailVerificationDTO) {
        try {
            // 检查是否是Outlook OAuth认证
            if ("outlook".equals(emailVerificationDTO.getEmailProvider())) {

                log.info("Outlook验证请求: {}", emailVerificationDTO);

                // 保存OAuth信息到数据库
                if (emailVerificationDTO.getClientId() != null && emailVerificationDTO.getTenantId() != null) {
                    UserEmail userEmail = new UserEmail();
                    userEmail.setUserId(UserContext.getUserId());
                    userEmail.setEmail(emailVerificationDTO.getEmailAddress());
                    userEmail.setEmailProvider(emailVerificationDTO.getEmailProvider());
                    userEmail.setEmailState(0); // 初始状态为未验证
                    userEmail.setCreatedTime(new Date());

                    // 设置OAuth信息
                    userEmail.setClientId(emailVerificationDTO.getClientId());
                    userEmail.setTenantId(emailVerificationDTO.getTenantId());
                    userEmail.setRedirectUri(emailVerificationDTO.getRedirectUri());
                    userEmail.setClientSecret(emailVerificationDTO.getClientSecret());

                    // 保存到数据库
                    emailService.saveUserEmailByOuth(userEmail);

                    log.info("已保存OAuth配置: clientId={}, tenantId={}",
                            emailVerificationDTO.getClientId(),
                            emailVerificationDTO.getTenantId());
                }

                boolean verified = emailVerificationService.verifyOutlookToken(
                        emailVerificationDTO.getEmailAddress()
                );
                // 设备码授权验证
//                boolean verified = emailVerificationService.verifyOutlookDeviceCode(
//                    emailVerificationDTO.getEmailAddress(),
//                    emailVerificationDTO.getAuthCode()
//                );
//
                if (verified) {
                    return Result.success(true, "Outlook设备码授权验证成功");
                } else {
                    return Result.error("Outlook设备码授权验证失败");
                }
            } else {
                // 普通授权码验证
                return emailVerificationService.verifyEmailCredentials(emailVerificationDTO);
            }
        } catch (Exception e) {
            log.error("验证邮箱凭证时发生异常: {}", e.getMessage(), e);
            return Result.error("验证邮箱凭证失败，请稍后重试");
        }
    }

    /**
     * 保存用户邮箱信息
     */
    @PostMapping("/save-email")
    public Result<Boolean> saveUserEmail(@RequestBody Map<String, Object> params) {
        try {
            // 打印接收到的所有参数
            log.info("接收到的邮箱保存参数: {}", params);

            String email = (String) params.get("email");
            String password = (String) params.get("password");
            Integer result = params.get("result") instanceof Integer ? (Integer) params.get("result") :
                    Integer.parseInt(params.get("result").toString());
            String emailProvider = params.get("emailProvider").toString();

            // 获取OAuth相关字段
            String clientId = (String) params.get("clientId");
            String tenantId = (String) params.get("tenantId");
            String redirectUri = (String) params.get("redirectUri");
            String clientSecret = (String) params.get("clientSecret");

            // 打印OAuth相关字段
            log.info("OAuth信息 - clientId: {}, tenantId: {}, redirectUri: {}, clientSecret长度: {}",
                    clientId, tenantId, redirectUri,
                    clientSecret != null ? clientSecret.length() : 0);

            if (email == null) {
                return Result.error("邮箱地址不能为空");
            }

            // 如果是Outlook邮箱且提供了OAuth信息，使用saveUserEmail方法
            if ("outlook".equals(emailProvider) && clientId != null && tenantId != null) {
                UserEmail userEmail = new UserEmail();
                userEmail.setUserId(UserContext.getUserId());
                userEmail.setEmail(email);
                userEmail.setEmailProvider(emailProvider);
                userEmail.setEmailState(result); // 设置验证状态
                userEmail.setCreatedTime(new Date());

                // 设置OAuth信息
                userEmail.setClientId(clientId);
                userEmail.setTenantId(tenantId);
                userEmail.setRedirectUri(redirectUri);
                userEmail.setClientSecret(clientSecret);

                // 如果有密码/设备码，也设置
                if (password != null && !password.isEmpty()) {
                    userEmail.setEmailPassword(password);
                }

                // 保存到数据库
                UserEmail savedEmail = emailService.saveUserEmail(userEmail);
                if (savedEmail != null) {
                    return Result.success(true, "邮箱信息保存成功");
                } else {
                    return Result.error("邮箱信息保存失败");
                }
            } else {
                // 对于其他邮箱类型，使用原有的saveEmailRecord方法
                if (password == null) {
                    return Result.error("授权码不能为空");
                }

                boolean saved = emailService.saveEmailRecord(email, password, result, emailProvider);
                if (saved) {
                    return Result.success(true, "邮箱信息保存成功");
                } else {
                    return Result.error("邮箱信息保存失败");
                }
            }
        } catch (Exception e) {
            log.error("保存用户邮箱信息时发生异常: {}", e.getMessage(), e);
            return Result.error("保存用户邮箱信息失败，请稍后重试");
        }
    }

    /**
     * 添加用户邮箱配置（仅添加，不验证）
     */
    @PostMapping("/add-email")
    public Result<UserEmail> addUserEmail(@RequestBody Map<String, Object> params) {
        try {
            String email = (String) params.get("email");
            String emailProvider = (String) params.get("emailProvider");
//            String oauthInfo = (String) params.get("oauthInfo"); // 获取OAuth信息

            if (email == null || email.trim().isEmpty()) {
                return Result.error("邮箱地址不能为空");
            }

            // 验证邮箱格式
            if (!email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$")) {
                return Result.error("邮箱格式不正确");
            }

            Long userId = UserContext.getUserId();

            // 检查是否已存在相同邮箱
            List<UserEmail> existingEmails = emailService.getAllUserEmails(userId);
            for (UserEmail existingEmail : existingEmails) {
                if (existingEmail.getEmail().equalsIgnoreCase(email)) {
                    return Result.error("该邮箱已存在，请勿重复添加");
                }
            }

            // 添加邮箱配置（状态为未验证）
            UserEmail userEmail;
//            if ("outlook".equals(emailProvider) && oauthInfo != null && !oauthInfo.isEmpty()) {
//                // 如果是Outlook邮箱，并且有OAuth信息，则保存OAuth信息
//                // 创建UserEmail对象
//                userEmail = new UserEmail();
//                userEmail.setUserId(userId);
//                userEmail.setEmail(email);
//                userEmail.setEmailProvider(emailProvider);
//                userEmail.setEmailState(0); // 未验证状态
//                userEmail.setCreatedTime(new Date());
//
//                // 将完整的OAuth JSON信息保存到数据库
//                userEmail.setClientId(getJsonValue(oauthInfo, "clientId"));
//                userEmail.setTenantId(getJsonValue(oauthInfo, "tenantId"));
//                userEmail.setRedirectUri(getJsonValue(oauthInfo, "redirectUri"));
//                userEmail.setClientSecret(getJsonValue(oauthInfo, "clientSecret"));
//
//                // 保存到数据库
//                userEmail = emailService.saveUserEmail(userEmail);
//            } else {
                // 其他邮箱类型，密码暂时为空，后续验证时再设置
                userEmail = emailService.addEmailConfig(email, emailProvider);
//            }

            if (userEmail != null) {
                return Result.success(userEmail, "邮箱添加成功");
            } else {
                return Result.error("邮箱添加失败");
            }
        } catch (Exception e) {
            log.error("添加用户邮箱配置时发生异常: {}", e.getMessage(), e);
            return Result.error("添加用户邮箱配置失败，请稍后重试");
        }
    }

    /**
     * 获取用户邮箱设置
     */
    @GetMapping("/get-user-email")
    public Result<UserEmail> getUserEmail() {
        try {
            Long userId = UserContext.getUserId();
            UserEmail userEmail = emailService.getUserEmailById(userId);
            return Result.success(userEmail);
        } catch (Exception e) {
            log.error("获取用户邮箱设置时发生异常: {}", e.getMessage(), e);
            return Result.error("获取用户邮箱设置失败，请稍后重试");
        }
    }

    /**
     * 获取当前用户已验证的邮箱列表
     */
    @GetMapping("/verified-emails")
    public Result<List<UserEmail>> getVerifiedEmails() {
        try {
            Long userId = UserContext.getUserId();
            List<UserEmail> verifiedEmails = emailService.getVerifiedEmails(userId);
            List<UserEmail> result = new ArrayList<>();
            for (UserEmail verifiedEmail : verifiedEmails) {
                verifiedEmail.setEmailPassword(null);
                verifiedEmail.setClientId(null);
                verifiedEmail.setAccessToken(null);
                verifiedEmail.setClientSecret(null);
                verifiedEmail.setRedirectUri(null);
                verifiedEmail.setTenantId(null);
                verifiedEmail.setRefreshToken(null);
                verifiedEmail.setUserId(null);
                result.add(verifiedEmail);
            }
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取已验证邮箱列表时发生异常: {}", e.getMessage(), e);
            return Result.error("获取已验证邮箱列表失败，请稍后重试");
        }
    }

    /**
     * 获取当前用户的所有邮箱配置（包括已验证和未验证的）
     */
    @GetMapping("/all-emails")
    public Result<List<UserEmail>> getAllUserEmails() {
        try {
            Long userId = UserContext.getUserId();
            List<UserEmail> allEmails = emailService.getAllUserEmails(userId);
            return Result.success(allEmails);
        } catch (Exception e) {
            log.error("获取所有邮箱配置时发生异常: {}", e.getMessage(), e);
            return Result.error("获取所有邮箱配置失败，请稍后重试");
        }
    }

    /**
     * 使用自定义邮箱发送邮件 - 处理application/json格式（用于纯文本邮件）
     */
    @PostMapping("/send-custom")
    public Result<Boolean> sendCustomEmail(@RequestBody CustomEmailSendDTO customEmailSendDTO) {
        try {
            // 验证必要参数
            if (customEmailSendDTO.getSenderEmail() == null || customEmailSendDTO.getRecipients() == null ||
                    customEmailSendDTO.getSubject() == null || customEmailSendDTO.getContent() == null) {
                log.error("邮件参数不完整");
                return Result.error("邮件参数不完整");
            }

            // 从后端获取授权码，而不是从前端传递
            Long userId = UserContext.getUserId();
            UserEmail userEmail = emailService.getUserEmailByUserIdAndEmail(userId, customEmailSendDTO.getSenderEmail());

            if (userEmail == null) {
                log.error("未找到用户ID为{}的邮箱{}", userId, customEmailSendDTO.getSenderEmail());
                return Result.error("未找到该邮箱的授权码，请确保邮箱已验证");
            }

            if (userEmail.getEmailState() != 1){
                log.error("找到用户ID为{}的邮箱{}，但未验证成功", userId, customEmailSendDTO.getSenderEmail());
                return Result.error("邮箱未验证成功，请重新验证");
            }

            if (!Objects.equals(userEmail.getEmailProvider(), "outlook")) {
                customEmailSendDTO.setSenderAuthCode(userEmail.getEmailPassword());
            }

            // 保存邮件
            boolean success = emailService.saveSendEmailRecord(customEmailSendDTO);

            if (success) {
                return Result.success(true, "邮件发送成功");
            } else {
                return Result.error("邮件发送失败，请检查邮箱配置或网络连接");
            }
        } catch (Exception e) {
            log.error("发送自定义邮件时发生异常: {}", e.getMessage(), e);
            return Result.error("邮件发送失败: " + e.getMessage());
        }
    }

    /**
     * 使用自定义邮箱发送邮件 - 处理application/json格式（用于纯文本邮件）
     */
//    @PostMapping("/send-custom")
    public Result<Boolean> saveCustomEmail(@RequestBody CustomEmailSendDTO customEmailSendDTO) {
        try {
            // 验证必要参数
            if (customEmailSendDTO.getSenderEmail() == null || customEmailSendDTO.getRecipients() == null ||
                    customEmailSendDTO.getSubject() == null || customEmailSendDTO.getContent() == null) {
                log.error("邮件参数不完整");
                return Result.error("邮件参数不完整");
            }

            // 从后端获取授权码，而不是从前端传递
            Long userId = UserContext.getUserId();
            UserEmail userEmail = emailService.getUserEmailByUserIdAndEmail(userId, customEmailSendDTO.getSenderEmail());

            if (userEmail == null) {
                log.error("未找到用户ID为{}的邮箱{}", userId, customEmailSendDTO.getSenderEmail());
                return Result.error("未找到该邮箱的授权码，请确保邮箱已验证");
            }

            if (userEmail.getEmailState() != 1){
                log.error("找到用户ID为{}的邮箱{}，但未验证成功", userId, customEmailSendDTO.getSenderEmail());
                return Result.error("邮箱未验证成功，请重新验证");
            }

            if (!Objects.equals(userEmail.getEmailProvider(), "outlook")) {
                customEmailSendDTO.setSenderAuthCode(userEmail.getEmailPassword());
            }

            // 保存邮件
            boolean success = customEmailService.sendCustomHtmlEmail(customEmailSendDTO);

            if (success) {
                return Result.success(true, "邮件发送成功");
            } else {
                return Result.error("邮件发送失败，请检查邮箱配置或网络连接");
            }
        } catch (Exception e) {
            log.error("发送自定义邮件时发生异常: {}", e.getMessage(), e);
            return Result.error("邮件发送失败: " + e.getMessage());
        }
    }

    /**
     * 使用自定义邮箱发送带附件的邮件 - 处理multipart/form-data格式
     */
    @PostMapping("/send-custom-with-attachments")
    public Result<Boolean> sendCustomEmailWithAttachments(
            @RequestParam("senderEmail") String senderEmail,
            @RequestParam("recipients") String recipients,
            @RequestParam("subject") String subject,
            @RequestParam("content") String content,
            @RequestParam(value = "cc", required = false) String cc,
            @RequestParam(value = "bcc", required = false) String bcc,
            @RequestParam(value = "attachments", required = false) List<MultipartFile> attachments) {
        try {
            // 验证必要参数
            if (senderEmail == null || recipients == null ||
                    subject == null || content == null) {
                log.error("邮件参数不完整");
                return Result.error("邮件参数不完整");
            }

            Long userId = UserContext.getUserId();
            UserEmail userEmail = emailService.getUserEmailByUserIdAndEmail(userId, senderEmail);
            if (userEmail == null){
                return Result.error("请检查邮箱是否正确");
            }

            // 构建DTO对象
            CustomEmailSendDTO customEmailSendDTO = new CustomEmailSendDTO();
            customEmailSendDTO.setSenderEmail(senderEmail);

            if (!Objects.equals(userEmail.getEmailProvider(), "outlook")) {
                customEmailSendDTO.setSenderAuthCode(userEmail.getEmailPassword());
            }
            customEmailSendDTO.setRecipients(recipients);
            customEmailSendDTO.setSubject(subject);
            customEmailSendDTO.setContent(content);
            customEmailSendDTO.setCc(cc);
            customEmailSendDTO.setBcc(bcc);
            customEmailSendDTO.setAttachments(attachments);

            // 保存邮件
            boolean success = emailService.saveSendEmailRecord(customEmailSendDTO);

            if (success) {
                return Result.success(true, "邮件发送成功");
            } else {
                return Result.error("邮件发送失败，请检查邮箱配置或网络连接");
            }
        } catch (Exception e) {
            log.error("发送自定义邮件时发生异常: {}", e.getMessage(), e);
            return Result.error("邮件发送失败: " + e.getMessage());
        }
    }

//    @PostMapping("/save-custom-with-attachments")
    public Result<Boolean> saveCustomEmailWithAttachments(
            @RequestParam("senderEmail") String senderEmail,
            @RequestParam("recipients") String recipients,
            @RequestParam("subject") String subject,
            @RequestParam("content") String content,
            @RequestParam(value = "cc", required = false) String cc,
            @RequestParam(value = "bcc", required = false) String bcc,
            @RequestParam(value = "attachments", required = false) List<MultipartFile> attachments) {
        try {
            // 验证必要参数
            if (senderEmail == null || recipients == null ||
                    subject == null || content == null) {
                log.error("邮件参数不完整");
                return Result.error("邮件参数不完整");
            }

            Long userId = UserContext.getUserId();
            UserEmail userEmail = emailService.getUserEmailByUserIdAndEmail(userId, senderEmail);
            if (userEmail == null){
                return Result.error("请检查邮箱是否正确");
            }

            // 构建DTO对象
            CustomEmailSendDTO customEmailSendDTO = new CustomEmailSendDTO();
            customEmailSendDTO.setSenderEmail(senderEmail);

            if (!Objects.equals(userEmail.getEmailProvider(), "outlook")) {
                customEmailSendDTO.setSenderAuthCode(userEmail.getEmailPassword());
            }
            customEmailSendDTO.setRecipients(recipients);
            customEmailSendDTO.setSubject(subject);
            customEmailSendDTO.setContent(content);
            customEmailSendDTO.setCc(cc);
            customEmailSendDTO.setBcc(bcc);

            // 发送邮件
            boolean success;
            if (attachments != null && !attachments.isEmpty()) {
                success = customEmailService.sendCustomAttachmentEmail(customEmailSendDTO, attachments);
            } else {
                success = customEmailService.sendCustomHtmlEmail(customEmailSendDTO);
            }

            if (success) {
                return Result.success(true, "邮件发送成功");
            } else {
                return Result.error("邮件发送失败，请检查邮箱配置或网络连接");
            }
        } catch (Exception e) {
            log.error("发送自定义邮件时发生异常: {}", e.getMessage(), e);
            return Result.error("邮件发送失败: " + e.getMessage());
        }
    }

    /**
     * 获取Outlook设备码授权信息
     */
    @PostMapping("/get-outlook-device-code")
    public Result<Map<String, String>> getOutlookDeviceCode(@RequestBody Map<String, Object> params) {
        try {
            String email = (String) params.get("email");
            Long userId = UserContext.getUserId();

            // 验证参数
            if (email == null || email.trim().isEmpty()) {
                return Result.error("邮箱地址不能为空");
            }


            // 获取邮箱配置信息
            UserEmail userEmail = null;
            if (userId != null) {
                userEmail = emailService.getUserEmailByUserIdAndEmail(userId, email);
            }

            if (userEmail == null) {
                // 如果没有找到邮箱配置，检查是否有clientId和tenantId
                String clientId = (String) params.get("clientId");
                String tenantId = (String) params.get("tenantId");

                if (clientId == null || clientId.trim().isEmpty() ||
                        tenantId == null || tenantId.trim().isEmpty()) {
                    return Result.error("缺少必要的OAuth配置信息");
                }

                // 使用提供的clientId和tenantId获取设备码
                Map<String, String> deviceCodeInfo = emailService.getOutlookDeviceCode(clientId, tenantId);
                return Result.success(deviceCodeInfo);
            } else {
                // 使用已保存的clientId和tenantId获取设备码
                if (userEmail.getClientId() == null || userEmail.getTenantId() == null) {
                    return Result.error("邮箱配置缺少必要的OAuth信息");
                }

                Map<String, String> deviceCodeInfo = emailService.getOutlookDeviceCode(
                        userEmail.getClientId(), userEmail.getTenantId());
                return Result.success(deviceCodeInfo);
            }
        } catch (Exception e) {
            log.error("获取Outlook设备码授权信息时发生异常: {}", e.getMessage(), e);
            return Result.error("获取设备码授权信息失败，请稍后重试");
        }
    }

    /**
     * 删除用户邮箱配置
     */
    @DeleteMapping("/delete-by-email")
    public Result<Boolean> deleteUserEmail(@RequestParam("email") String email) {
        try {
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                log.error("获取用户ID失败，用户未登录或登录已过期");
                return Result.error("未登录或登录已过期");
            }
            
            // 验证邮箱所有权
//            UserEmail existingEmail = emailService.getUserEmailById(userId, email);
//            if (existingEmail == null) {
//                return Result.error("邮箱配置不存在");
//            }
//
//            if (!existingEmail.getUserId().equals(userId)) {
//                return Result.error("无权删除该邮箱配置");
//            }
            
            // 删除邮箱配置
            boolean success = emailService.deleteUserEmail(userId, email) > 0;
            
            if (success) {
                return Result.success(true, "邮箱配置删除成功");
            } else {
                return Result.error("删除失败，邮箱配置不存在或已被删除");
            }
        } catch (Exception e) {
            log.error("删除用户邮箱配置时发生异常: {}", e.getMessage(), e);
            return Result.error("删除邮箱配置失败，请稍后重试");
        }
    }

    /**
     * 修改用户邮箱配置
     */
    @PutMapping("/update-email")
    public Result<Boolean> updateUserEmail(@RequestBody Map<String, Object> params) {
        try {
            Long userId = UserContext.getUserId();
            if (userId == null) {
                log.error("获取用户ID失败，用户未登录或登录已过期");
                return Result.error("未登录或登录已过期");
            }

            // 获取ID
            Long id = null;
            if (params.get("id") instanceof Integer) {
                id = ((Integer) params.get("id")).longValue();
            } else if (params.get("id") instanceof Long) {
                id = (Long) params.get("id");
            } else if (params.get("id") instanceof String) {
                id = Long.parseLong((String) params.get("id"));
            }

            if (id == null) {
                return Result.error("邮箱配置ID不能为空");
            }

            // 验证邮箱所有权
            UserEmail existingEmail = emailService.getUserEmailById(id);
            if (existingEmail == null) {
                return Result.error("邮箱配置不存在");
            }

            if (!existingEmail.getUserId().equals(userId)) {
                return Result.error("无权修改该邮箱配置");
            }

            // 获取参数
            String email = (String) params.get("email");
            String emailProvider = (String) params.get("emailProvider");
            String emailPassword = (String) params.get("emailPassword");
            String clientId = (String) params.get("clientId");
            String tenantId = (String) params.get("tenantId");
            String redirectUri = (String) params.get("redirectUri");
            String clientSecret = (String) params.get("clientSecret");

            // 验证必填参数
            if (email == null || email.trim().isEmpty() || emailProvider == null || emailProvider.trim().isEmpty()) {
                return Result.error("邮箱地址和邮箱提供商不能为空");
            }

            // 验证邮箱格式
            if (!email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$")) {
                return Result.error("邮箱格式不正确");
            }

            // 根据邮箱类型验证其他参数
            if ("outlook".equals(emailProvider)) {
                if (clientId == null || clientId.trim().isEmpty() ||
                    tenantId == null || tenantId.trim().isEmpty() ||
                    clientSecret == null || clientSecret.trim().isEmpty()) {
                    return Result.error("Outlook邮箱配置信息不完整");
                }
            } else {
                if (emailPassword == null || emailPassword.trim().isEmpty()) {
                    return Result.error("邮箱授权码不能为空");
                }
            }

            // 创建UserEmail对象
            UserEmail userEmail = new UserEmail();
            userEmail.setId(id);
            userEmail.setUserId(userId);
            userEmail.setEmail(email);
            userEmail.setEmailProvider(emailProvider);
            userEmail.setEmailState(0); // 修改后重置为未验证状态
            userEmail.setUpdateTime(new Date());

            // 根据邮箱类型设置不同字段
            if ("outlook".equals(emailProvider)) {
                userEmail.setClientId(clientId);
                userEmail.setTenantId(tenantId);
                userEmail.setRedirectUri(redirectUri);
                userEmail.setClientSecret(clientSecret);
            } else {
                userEmail.setEmailPassword(emailPassword);
            }

            // 更新邮箱配置
            int updatedEmail = emailService.updateUserEmail(userEmail);
            if (updatedEmail > 0) {
                EmailVerificationDTO emailVerificationDTO = new EmailVerificationDTO();
                emailVerificationDTO.setEmailAddress(email);
                emailVerificationDTO.setAuthCode(emailPassword);
                emailVerificationDTO.setEmailProvider(emailProvider);

                if (!emailProvider.equals("outlook")) {
                    return emailVerificationService.verifyEmailCredentials(emailVerificationDTO);
                }else {
                    boolean b = emailVerificationService.verifyOutlookToken(email);
                    if (b) {
                        return Result.success(true, "验证成功");
                    }else {
                        return Result.error("验证失败");
                    }
                }
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            log.error("修改用户邮箱配置时发生异常: {}", e.getMessage(), e);
            return Result.error("修改邮箱配置失败，请稍后重试");
        }
    }

    /**
     * 下载附件
     */
    @GetMapping("/download-attachment")
    public ResponseEntity<byte[]> downloadAttachment(@RequestParam("path") String path) {
        try {
            // 校验用户权限
//            Long userId = UserContext.getUserId();
//            if (userId == null) {
//                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
//                    .body("未登录或登录已过期".getBytes(StandardCharsets.UTF_8));
//            }
            
            // 构建完整的文件路径
            String basePath = attachmentsPath;
            String fullPath = basePath + File.separator + path;
            
            File file = new File(fullPath);
            if (!file.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("附件不存在".getBytes(StandardCharsets.UTF_8));
            }
            
            // 读取文件内容
            byte[] fileContent = Files.readAllBytes(file.toPath());
            
            // 从路径中提取文件名
            String originalFilename = file.getName();
            String encodedFilename = URLEncoder.encode(originalFilename, StandardCharsets.UTF_8);
            
            // 设置HTTP头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFilename + "\"");
            headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()));
            headers.add(HttpHeaders.CONTENT_TYPE, Files.probeContentType(file.toPath()));
            
            return ResponseEntity.ok()
                .headers(headers)
                .body(fileContent);
        } catch (Exception e) {
            log.error("下载附件出错", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(("下载附件失败: " + e.getMessage()).getBytes(StandardCharsets.UTF_8));
        }
    }

    /**
     * 获取附件预览URL
     */
    @GetMapping("/attachment-preview-url")
    public Result<String> getAttachmentPreviewUrl(@RequestParam("path") String path) {
        try {
            // 不再检查用户权限，直接处理文件
            // 构建完整的文件路径
            String basePath = attachmentsPath;
            String fullPath = basePath + File.separator + path;

            File file = new File(fullPath);
            if (!file.exists()) {
                return Result.error("附件不存在");
            }

            // 获取文件类型
            String contentType = Files.probeContentType(file.toPath());

            // 检查是否是可预览的文件类型
            if (contentType != null && (
                    contentType.startsWith("image/") ||
                            contentType.equals("application/pdf") ||
                            contentType.equals("text/plain"))) {

                // 生成预览URL
                String token = UUID.randomUUID().toString();
                // 使用相对路径，前端自动拼接域名
                String previewUrl = "/api/email/preview-attachment?path=" +
                        URLEncoder.encode(path, "UTF-8") + "&token=" + token;

                return Result.success(previewUrl);
            } else {
                return Result.error("不支持该文件类型的预览");
            }
        } catch (Exception e) {
            log.error("获取附件预览URL时发生异常: {}", e.getMessage(), e);
            return Result.error("获取预览URL失败: " + e.getMessage());
        }
    }

    /**
     * 预览附件 - 使用ResponseEntity返回文件
     */
    @GetMapping("/preview-attachment")
    public ResponseEntity<byte[]> previewAttachment(
            @RequestParam("path") String path,
            @RequestParam(value = "token", required = false) String token) {
        try {
            // 构建完整的文件路径
            String basePath = attachmentsPath;
            String fullPath = basePath + File.separator + path;

            File file = new File(fullPath);
            if (!file.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body("附件不存在".getBytes());
            }

            // 获取文件类型
            String contentType = Files.probeContentType(file.toPath());
            if (contentType == null) {
                // 根据扩展名猜测内容类型
                String extension = path.substring(path.lastIndexOf(".") + 1).toLowerCase();
                switch (extension) {
                    case "jpg":
                    case "jpeg":
                        contentType = "image/jpeg";
                        break;
                    case "png":
                        contentType = "image/png";
                        break;
                    case "gif":
                        contentType = "image/gif";
                        break;
                    case "pdf":
                        contentType = "application/pdf";
                        break;
                    case "txt":
                        contentType = "text/plain";
                        break;
                    default:
                        contentType = "application/octet-stream";
                        break;
                }
            }

            // 读取文件内容
            byte[] fileContent = Files.readAllBytes(file.toPath());

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(contentType));
            headers.setContentLength(fileContent.length);

            return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("预览附件时发生异常: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("预览附件失败: " + e.getMessage()).getBytes());
        }
    }

    /**
     * 直接下载附件 - 不使用ResponseEntity返回，直接输出流
     */
    @GetMapping("/download-attachment-direct")
    public void downloadAttachmentDirect(@RequestParam("path") String path, HttpServletResponse response) {
        try {
            // 校验用户权限
            Long userId = UserContext.getUserId();
            if (userId == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("未登录或登录已过期");
                return;
            }
            
            // 构建完整的文件路径
            String basePath = attachmentsPath;
            String fullPath = basePath + File.separator + path;
            
            File file = new File(fullPath);
            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("附件不存在");
                return;
            }

            // 从文件名中提取原始文件名
            String originalFilename;
            if (path.contains(File.separator)) {
                originalFilename = path.substring(path.lastIndexOf(File.separator) + 1);
            } else {
                originalFilename = path;
            }
            
            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            
            // 解决中文文件名乱码问题
            String encodedFilename = URLEncoder.encode(originalFilename, StandardCharsets.UTF_8);
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFilename + "\"");
            response.setContentLengthLong(file.length());
            
            // 输出文件流
            try (InputStream inputStream = Files.newInputStream(file.toPath());
                 OutputStream outputStream = response.getOutputStream()) {
                
                // 使用缓冲区复制数据
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            }
        } catch (Exception e) {
            log.error("直接下载附件时发生异常: {}", e.getMessage(), e);
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("下载附件失败: " + e.getMessage());
            } catch (IOException ex) {
                log.error("写入错误响应时发生异常: {}", ex.getMessage(), ex);
            }
        }
    }

    /**
     * 检查附件是否存在
     */
    @GetMapping("/check-attachment-exists")
    public ResponseEntity<Void> checkAttachmentExists(@RequestParam("path") String path) {
        try {
            // 构建完整的文件路径
            String basePath = attachmentsPath;
            String fullPath = basePath + File.separator + path;

            File file = new File(fullPath);
            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }

            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.error("检查附件存在性时出错", e);
            return ResponseEntity.internalServerError().build();
        }
    }
} 